import { Empty, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { tickersApi } from '@/api';
import { handleContractSort, lunXunTime } from '@/utils/helper';
import { useInterval } from 'ahooks';

export default function ContractList({ contractList }: any) {
  const [list, setList] = useState<any>([]);
  const [name, setName] = useState<string>('');

  useEffect(() => {
    if (contractList && contractList.length > 0) {
      setList(handleContractSort(contractList));
    }
  }, [contractList]);

  // 开始轮询
  useInterval(() => {
    getContractTickers();
  }, lunXunTime);

  // 合约行情-all
  async function getContractTickers() {
    console.log('合约行情-all-s');
    const val: any = await tickersApi();
    console.log('合约行情-all', val);
    setList(handleContractSort(val));
  }

  // changeIpt
  function changeIpt(e: any) {
    const val = e.target.value.trim();
    setName(val);
    let _list: any = [...contractList];
    if (val.length > 0)
      _list = contractList.filter((item: any) => item?.contract.includes(val.toUpperCase()));
    setList(_list);
  }

  function rowClick(e: any) {
    window.location.href = `/home?contract=${e.contract}`;
  }

  return (
    <div className="ContractListWrap">
      <div className="iptwrap">
        <Input
          prefix={<SearchOutlined />}
          style={{ width: '380px' }}
          size="large"
          value={name}
          onChange={changeIpt}
          placeholder="搜索"
        />
      </div>
      <div className="clistrap">
        <div className="crow crowTh">
          <div className="citem">市场</div>
          <div className="citem">价格</div>
          <div className="citem">涨跌幅</div>
        </div>
        <div className="clcon">
          {list &&
            list.map((item: any, i: number) => (
              <div className="crow crowtr" key={i} onClick={() => rowClick(item)}>
                <div className="citem">{item?.contract}</div>
                <div className="citem">{item?.last}</div>
                <div className="citem">
                  <span className={`${item?.change_percentage > 0 ? 'color-red' : 'color-green'}`}>
                    {item?.change_percentage}%
                  </span>
                </div>
              </div>
            ))}
          {list.length === 0 && (
            <div className="emptyWrap">
              <Empty />
            </div>
          )}
        </div>
      </div>
      <div className="xxxx"></div>
    </div>
  );
}
